<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <!-- 修改后的调出药库ID搜索下拉框 -->
      <el-form-item label="调出药库ID" prop="warehouseId" label-width="80">
        <el-select
          v-model="queryParams.warehouseId"
          placeholder="请选择调出药库"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in warehouseOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 修改后的调入药房ID搜索下拉框 -->
      <el-form-item label="调入药房ID" prop="pharmacyId" label-width="80">
        <el-select
          v-model="queryParams.pharmacyId"
          placeholder="请选择调入药房"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in pharmacyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 修改后的药品ID搜索下拉框 -->
      <el-form-item label="药品ID" prop="drugId">
        <el-select
          v-model="queryParams.drugId"
          placeholder="请选择药品"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in drugOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="状态" prop="transferStatus">
        <el-select v-model="queryParams.transferStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_oper_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['drug_transfer:drug_transfer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['drug_transfer:drug_transfer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['drug_transfer:drug_transfer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['drug_transfer:drug_transfer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drug_transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="调单序号" align="center" prop="transferId" />

      <!-- 修改调出药库ID列 -->
      <el-table-column label="调出药库ID" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.warehouseId }} ({{ getWarehouseName(scope.row.warehouseId) }})</span>
        </template>
      </el-table-column>
      <!-- 修改调入药房ID列 -->
      <el-table-column label="调入药房ID" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pharmacyId }} ({{ getPharmacyName(scope.row.pharmacyId) }})</span>
        </template>
      </el-table-column>
      <!-- 修改药品ID列 -->
      <el-table-column label="药品ID" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.drugId }} ({{ getDrugName(scope.row.drugId) }})</span>
        </template>
      </el-table-column>

      <el-table-column label="调拨数量" align="center" prop="quantity" />
      <el-table-column label="状态" align="center" prop="transferStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_oper_type" :value="scope.row.transferStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['drug_transfer:drug_transfer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['drug_transfer:drug_transfer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品从药库调到药房对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 调出药库ID下拉框 -->
        <el-form-item label="调出药库ID" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择调出药库"
            clearable
            filterable
            @change="handleWarehouseChange"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 调入药房ID下拉框 -->
        <el-form-item label="调入药房ID" prop="pharmacyId">
          <el-select
            v-model="form.pharmacyId"
            placeholder="请选择调入药房"
            clearable
            filterable
          >
            <el-option
              v-for="item in pharmacyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 药品ID下拉框 - 添加change事件 -->
        <el-form-item label="药品ID" prop="drugId">
          <el-select
            v-model="form.drugId"
            placeholder="请选择药品"
            clearable
            filterable
            @change="handleDrugChange"
          >
            <el-option
              v-for="item in filteredDrugOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 新增库存显示项 -->
        <el-form-item label="库存" prop="stockQuantity" v-show="form.drugId && form.warehouseId">
          <span>{{ stockQuantity }}</span>
        </el-form-item>

        <el-form-item label="调拨数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入调拨数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//此处需要查询到药库，药房，药品的id,整合时需要修改路径
import { listDrug_transfer, getDrug_transfer, delDrug_transfer, addDrug_transfer, updateDrug_transfer } from "@/api/drug_transfer/drug_transfer"
import { listDrug_warehouse } from "@/api/warehouse/drug_warehouse"
import drugAndPharmacy from "@/api/pharmacy/mixins/drugAndPharmacy.js"
import { listPharmacy } from "@/api/pharmacy/pharmacy"
import { listDrug } from "@/api/pharmacy/drug"; // 使用药品管理界面的API
import { listDrug_warehouse_stock } from "@/api/warehouse/drug_warehouse_stock"; // 新增导入药库库存API

export default {
  name: "Drug_transfer",
  dicts: ['sys_oper_type'],
  mixins: [drugAndPharmacy],
  data() {
    return {
      // 新增属性：库存量
      stockQuantity: '未选择',
      // 新增属性：过滤后的药品选项
      filteredDrugOptions: [],

      // 新增下拉选项数据
      warehouseOptions: [], // 药库下拉选项
      pharmacyOptions: [],  // 药房下拉选项
      drugOptions: [],      // 药品下拉选项

      // 新增映射数据
      warehouseMap: new Map(), // 药库ID到名称的映射
      pharmacyMap: new Map(),  // 药房ID到名称的映射
      drugMap: new Map(),      // 药品ID到名称的映射

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品从药库调到药房表格数据
      drug_transferList: [],
      // 药品表格数据
      drugList: [],
      // 药房表格数据
      pharmacyList: [],
      //药库表格数据
      warehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        pharmacyId: null,
        drugId: null,
        transferStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "调出药库ID不能为空", trigger: "blur" }
        ],
        pharmacyId: [
          { required: true, message: "调入药房ID不能为空", trigger: "blur" }
        ],
        drugId: [
          { required: true, message: "药品ID不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "调拨数量不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    // 先加载基础数据
    Promise.all([
      this.getWarehouseList(),
      this.getPharmacyList(),
      this.getDrugList()
    ]).then(() => {
      // 基础数据加载完成后，再加载表格数据
      this.getList();
    }).catch(error => {
      console.error("初始化数据加载失败：", error);
    });
  },
  methods: {
    /** 处理药品选择变化事件 */
    handleDrugChange(drugId) {
      if (drugId && this.form.warehouseId) {
        this.getStockQuantity();
      } else {
        this.stockQuantity = '未选择';
      }
    },
    /** 获取药品库存量 */
    getStockQuantity() {
      if (!this.form.warehouseId || !this.form.drugId) {
        this.stockQuantity = '未选择';
        return;
      }

      // 调用药库库存API获取库存量
      listDrug_warehouse_stock({
        warehouseId: this.form.warehouseId,
        drugId: this.form.drugId,
        pageSize: 1
      }).then(response => {
        if (response.rows && response.rows.length > 0) {
          this.stockQuantity = response.rows[0].quantity;
        } else {
          this.stockQuantity = '0 (无库存记录)';
        }
      }).catch(error => {
        console.error("获取库存失败：", error);
        this.stockQuantity = '获取失败';
      });
    },

    /** 处理药库选择变化事件 */
    handleWarehouseChange(warehouseId) {
      if (warehouseId) {
        // 获取该药库的药品库存
        listDrug_warehouse_stock({
          warehouseId: warehouseId,
          pageSize: 1000
        }).then(response => {
          // 从库存记录中提取药品ID
          const drugIdsInWarehouse = response.rows.map(item => String(item.drugId));

          // 过滤药品选项，只显示该药库中存在的药品
          this.filteredDrugOptions = this.drugOptions.filter(option =>
            drugIdsInWarehouse.includes(option.value)
          );
        }).catch(error => {
          console.error("获取药库库存失败：", error);
          // 出错时显示所有药品
          this.filteredDrugOptions = [...this.drugOptions];
        });
      } else {
        // 未选择药库时显示所有药品
        this.filteredDrugOptions = [...this.drugOptions];
      }

      // 重置药品ID选择
      this.form.drugId = null;
      // 如果药品ID已选择，更新库存显示
      if (this.form.drugId) {
        this.getStockQuantity();
      } else {
        this.stockQuantity = '未选择';
      }
    },

    /** 查询药品从药库调到药房列表 */
    getList() {
      this.loading = true
      listDrug_transfer(this.queryParams).then(response => {
        this.drug_transferList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 获取药房列表数据并生成下拉选项 - 修正版 */
    getPharmacyList() {
      return new Promise((resolve, reject) => {
        listPharmacy({
          pageSize: 1000,
          isValid: 1
        }).then(response => {
          this.pharmacyList = response.rows;
          this.pharmacyMap = new Map();
          this.pharmacyOptions = []; // 清空选项

          response.rows.forEach(item => {
            const id = String(item.pharmacyId);
            this.pharmacyMap.set(id, item.pharmacyName);
            this.pharmacyOptions.push({
              value: id,
              label: `${item.pharmacyName} (ID: ${id})`
            });
          });
          resolve();
        }).catch(error => {
          console.error("获取药房列表失败：", error);
          reject(error);
        });
      });
    },

    /** 获取药品列表数据并生成下拉选项 - 修正版 */
    getDrugList() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        listDrug({
          pageSize: 1000,
          isValid: 1
        }).then(response => {
          this.drugList = response.rows;
          this.drugMap = new Map();
          this.drugOptions = []; // 清空选项

          response.rows.forEach(item => {
            if (item.drugId && item.drugName) {
              const id = String(item.drugId);
              this.drugMap.set(id, item.drugName);
              this.drugOptions.push({
                value: id,
                label: `${item.drugName} (ID: ${id})`
              });
            }
          });
          resolve();
        }).catch(error => {
          console.error("获取药品列表失败：", error);
          reject(error);
        }).finally(() => {
          this.loading = false;
        });
      });
    },

    /** 根据药房ID获取药房名称 - 修正版 */
    getPharmacyName(pharmacyId) {
      if (pharmacyId === null || pharmacyId === undefined) {
        return '无药房ID';
      }
      const id = String(pharmacyId);
      const name = this.pharmacyMap.get(id) || '未知药房';
      console.log(`获取药房名称: ID=${id}(${typeof id}), Name=${name}`);
      return name;
    },

    /** 根据药品ID获取药品名称 - 修正版 */
    getDrugName(drugId) {
      if (drugId === null || drugId === undefined) {
        console.warn("药品ID为空");
        return '无药品ID';
      }

      // 统一转换为字符串比较
      const id = String(drugId);

      if (!this.drugMap.size) {
        console.warn("药品映射表为空");
        return '映射表未初始化';
      }

      const name = this.drugMap.get(id) || '未知药品';

      console.log(`获取药品名称详情:
      输入ID: ${drugId} (类型: ${typeof drugId})
      转换后ID: ${id} (类型: ${typeof id})
      获取结果: ${name}
      映射表大小: ${this.drugMap.size}
      是否存在该ID: ${this.drugMap.has(id)}`);

      return name;
    },

    /** 获取药库列表数据并生成下拉选项 */
    getWarehouseList() {
      return new Promise((resolve, reject) => {
        listDrug_warehouse({
          pageSize: 1000,
          isValid: 1 // 只查询启用的药库
        }).then(response => {
          this.warehouseList = response.rows;
          this.warehouseMap = new Map();
          this.warehouseOptions = []; // 清空选项

          // 建立ID到名称的映射和生成下拉选项
          response.rows.forEach(item => {
            this.warehouseMap.set(item.warehouseId, item.warehouseName);
            this.warehouseOptions.push({
              value: item.warehouseId,
              label: `${item.warehouseName} (ID: ${item.warehouseId})`
            });
          });
          resolve();
        }).catch(error => {
          console.error("获取药库列表失败：", error);
          reject(error);
        });
      });
    },


    /** 根据药库ID获取药库名称 */
    getWarehouseName(warehouseId) {
      return this.warehouseMap.get(warehouseId) || '未知药库'
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        transferId: null,
        warehouseId: null,
        pharmacyId: null,
        drugId: null,
        quantity: null,
        transferStatus: null,
        applyTime: null,
        confirmTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transferId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加药品从药库调到药房";

      // 初始化过滤后的药品选项
      this.filteredDrugOptions = [...this.drugOptions];

      // 重置库存显示
      this.stockQuantity = '未选择';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transferId = row.transferId || this.ids;
      getDrug_transfer(transferId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改药品从药库调到药房";

        // 根据当前药库ID初始化药品选项
        if (this.form.warehouseId) {
          this.handleWarehouseChange(this.form.warehouseId);
        } else {
          this.filteredDrugOptions = [...this.drugOptions];
        }

        // 如果药品ID已存在，获取库存量
        if (this.form.drugId) {
          this.getStockQuantity();
        } else {
          this.stockQuantity = '未选择';
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.transferId != null) {
            updateDrug_transfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDrug_transfer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transferIds = row.transferId || this.ids
      this.$modal.confirm('是否确认删除药品从药库调到药房编号为"' + transferIds + '"的数据项？').then(function() {
        return delDrug_transfer(transferIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('drug_transfer/drug_transfer/export', {
        ...this.queryParams
      }, `drug_transfer_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
